package cn.edu.swu.wn.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

// 注解配置：访问路径为 /echo
@WebServlet("/echo")
public class EchoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置响应类型
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // 输出一个简单的表单，让用户输入内容
        out.println("<html>");
        out.println("<head><title>回声功能</title></head>");
        out.println("<body>");
        out.println("<form method='post' action='/mywebapp/echo'>"); // 表单提交到当前Servlet
        out.println("请输入内容：<input type='text' name='message' />");
        out.println("<input type='submit' value='提交' />");
        out.println("</form>");
        out.println("</body></html>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // 获取表单字段（与HTML中name属性对应）
        String username = request.getParameter("username");
        String userpass = request.getParameter("userpass");
        String gender = request.getParameter("gender");
        String[] classes = request.getParameterValues("class"); // 复选框可能有多个值

        // 输出结果
        out.println("<html><body>");
        out.println("<h1>提交结果：</h1>");
        out.println("用户名：" + username + "<br>");
        out.println("密码：" + userpass + "<br>");
        out.println("性别：" + gender + "<br>");
        out.println("课程：" + String.join(",", classes) + "<br>");
        out.println("</body></html>");
    }
}
